
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.common.IUploadService;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessSignContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuConfig;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuMerchantAccessCommonParamsHandle;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/09/26 10:25
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class HuiFuMerchantAccessInfoHandler extends HuiFuMerchantAccessCommonParamsHandle {

    private final IUploadService uploadService;

    /**
     * 进件
     * 
     * @param channelMerchantAccessContext
     */
    public void merchantAccess(ChannelMerchantAccessContext channelMerchantAccessContext) {
        log.info("汇付渠道提交进件 请求参数:{}", JsonUtils.toJsonString(channelMerchantAccessContext));
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessInfo();
        String subMchId = merchantAccessInfo.getSubMchId();
        MerchantEnum.MERCHANT_TYPE merchantType = MerchantEnum.MERCHANT_TYPE.from(merchantAccessInfo.getType());
        CommonResult<HuiFuConfig> commonResult = huiFuConfig(channelMerchantAccessContext.getProviderChannelConfig(), channelMerchantAccessContext.isTest());
        if (!commonResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(commonResult.getMsg());
            return;
        }
        // 配置转换
        HuiFuConfig huiFuConfig = commonResult.getData();
        switch (merchantType) {
            case PERSONAL:
                HuiFuMerchantRequestHandle.personAccess(huiFuConfig, channelMerchantAccessContext);
                break;
            default:
                HuiFuMerchantRequestHandle.companyAccess(huiFuConfig, channelMerchantAccessContext);
        }
        // 需要开通业务 因为修改的时候必填签约人信息 故 无需再次调用
        if (channelMerchantAccessContext.isProcessStatus() ) {
            if(!StringUtils.hasText(subMchId)){
                HuiFuMerchantRequestHandle.businessOpenRequest(huiFuConfig, channelMerchantAccessContext);
            }else {
                HuiFuMerchantRequestHandle.businessUpdateRequest(huiFuConfig, channelMerchantAccessContext);
            }
        }
    }

    /**
     * 进件查询
     * 
     * @param channelMerchantAccessQueryContext
     */
    public void merchantAccessQuery(ChannelMerchantAccessQueryContext channelMerchantAccessQueryContext) {
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantAccessQueryContext.getMerchantAccessInfo();
        CommonResult<HuiFuConfig> configCommonResult = huiFuConfig(channelMerchantAccessQueryContext.getProviderChannelConfig(), channelMerchantAccessQueryContext.isTest());
        // 配置转换
        HuiFuConfig huiFuConfig = configCommonResult.getData();
        HuiFuMerchantRequestHandle.accessQueryRequest(huiFuConfig, channelMerchantAccessQueryContext);
        List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessQueryContext.getMerchantAccessAuthList();
        Map<String, MerchantAccessAuthDO> merchantAccessAuthDOMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(channelMerchantAccessQueryContext.getMerchantAccessAuthDbList())) {
            merchantAccessAuthDOMap = channelMerchantAccessQueryContext.getMerchantAccessAuthDbList().stream()
                    .collect(Collectors.toMap(merchantAccessAuthDO -> merchantAccessAuthDO.getSubMchId(), Function.identity(), (t1, t2) -> t1));
        }
        if (!CollectionUtils.isEmpty(merchantAccessAuthList)) {
            Map<String, MerchantAccessAuthDO> finalMerchantAccessAuthDOMap = merchantAccessAuthDOMap;
            merchantAccessAuthList.stream().forEach(merchantAccessAuthDO -> {
                merchantAccessAuthDO.setSn(merchantAccessInfoDO.getSn());
                merchantAccessAuthDO.setAccessId(merchantAccessInfoDO.getId());
                MerchantAccessAuthDO accessAuthDO = finalMerchantAccessAuthDOMap.get(merchantAccessAuthDO.getSubMchId());
                if ((accessAuthDO == null || !StringUtils.hasText(accessAuthDO.getAuthUrl())) && merchantAccessAuthDO.getQrCodeArray() != null
                        && merchantAccessAuthDO.getQrCodeArray().length > 0) {
                    CommonResult<String> commonResult = uploadService.upload(merchantAccessAuthDO.getQrCodeArray(), CommonEnum.OssEnum.IMAGE);
                    if (commonResult.isSuccess()) {
                        merchantAccessAuthDO.setAuthUrl(commonResult.getData());
                    }
                    else {
                        log.error("斗拱授权查询图片上传失败:{}", commonResult.getMsg());
                    }
                }
            });
        }
    }

    /**
     * 业务开通
     * 
     * @param channelMerchantBusinessContext
     */
    public void merchantBusinessOpen(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HuiFuConfig> commonResult = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest());
        // 配置转换
        HuiFuConfig huiFuConfig = commonResult.getData();
        // HuiFuMerchantRequestHandle.businessOpenRequest(huiFuConfig,
        // channelMerchantBusinessContext);
        channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_CONFIG);
        channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_SUCCESS);
    }

    public void merchantSignQuery(ChannelMerchantAccessSignContext channelMerchantAccessQueryContext) {
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantAccessQueryContext.getMerchantAccessInfoDO();
        // if (!StringUtils.hasText(merchantAccessInfoDO.getApplyNo()) &&
        // !StringUtils.hasText(merchantAccessInfoDO.getSubMchId())) {
        // channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
        // channelMerchantAccessQueryContext.setRemark("申请单号和商户号不能都为空");
        // return;
        // }
        // if (!StringUtils.hasText(merchantAccessInfoDO.getApplyNo()) &&
        // StringUtils.hasText(merchantAccessInfoDO.getSubMchId())) {
        // // 汇付存在商户id 没有申请单id 说明已经自动审核通过
        // channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
        // // 汇付没有签约 直接进入待配置 即 merchantBusinessOpen 状态
        // channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
        // return;
        // }
        CommonResult<HuiFuConfig> commonResult = huiFuConfig(channelMerchantAccessQueryContext.getProviderChannelConfig(), channelMerchantAccessQueryContext.isTest());
        // 配置转换
        HuiFuConfig huiFuConfig = commonResult.getData();
        HuiFuMerchantRequestHandle.signQueryRequest(huiFuConfig, channelMerchantAccessQueryContext);
    }
}
